<template>
    <div class="modal-overlay" @click="closeModal" >
        <div class="modal-content" @click.stop>
            <div class="rounded-rectangle">
                <div class="leftrounded" >
                    <el-carousel :interval="0" :autoplay="false"  arrow="always" height="100%" >
                        <el-carousel-item v-for= "(image,index) in imageUrls" :key="index">
                            <a :href="image" target="_blank">
                                <img :src="image" alt="image" class="carousel-image"/>
                            </a>
                        </el-carousel-item>
                    </el-carousel>
                </div>
                <div class="rightrounded">
                    <el-scrollbar class="right-content-scrollbar">
                        <!-- 第一块，占比10% -->
                        <div class="demo-type-section"  style="display: flex; align-items: center; justify-content: space-between; height: 10%;">
                            <el-avatar
                                :class="'avatar'"  :src="ProfilePhoto"
                                :fit="'cover'"  :shape="'circle'"  :size="50"
                                @click="avaClick"
                            />
                            <p style="font-size: 20px; margin-left: 15px;">{{UName}}</p>
                            <span style="flex-grow: 1;"></span>
                            <el-button v-if="userID !== AuthorID"  color="#FFD466" type="warning" class="large-button"
                                        :class="{ 'followed-button': isFollow }"  @click="handleFollowClick">
                                {{ buttonText }}
                            </el-button>
                        </div>
                        <!-- 第二块，占比45% -->
                        <div class="title-section" style="min-height: 0; display: flex; flex-direction: column;">
                            <div class="text-box">
                                <p class="title">{{title}}</p>
                                <p class="content">{{content}}</p>
                                <div style="display: flex; align-items: center; justify-content: space-between;">
                                    <el-icon color="#FFD466" :size="25" font-weight: bold><Location/></el-icon>
                                    <p class="vocation">{{vocation}}</p>
                                    <span style="flex-grow: 1;"></span>
                                    <p class="vocation">{{time}}</p>
                                </div>
                            </div>
                        </div>
                        <!-- 第三块，占比37% -->
                        <div class="comments" style="height: 37%;">
                            <hr style="width: 98%; margin-top: -5px; margin-bottom:5px; color: grey ">
                            <CommentList :comments="comments" :isAdopt=true  :textcount="textcounter" @updateTextCounter="updateTextCounter" @toggle-replies="toggleReplies" />
                        </div>
                    </el-scrollbar>
                    <!-- 第四块，占比10% -->
                    <div class="button-container-section" style="display: flex; align-items: center; justify-content: space-between; height: 10%;position: relative; bottom: 0; background-color: white;">
                        <div v-if="!isInputVisible" class="comment-apply">
                            <el-button round
                                       class="custom-button"
                                       :hover="{ backgroundColor: '#f0f0f0' }"
                                       @click="firstcomment">
                                <el-avatar
                                    :class="'avatar'"
                                    :src="UserAvatar"
                                    :fit="'cover'"
                                    :shape="'circle'"
                                    :size="40"
                                />
                                <p style="font-family: Arial, sans-serif; font-size: 20px; font-weight: bold;  margin-left: 10px; margin-right: 90px; color: rgba(0, 0, 0, 0.3);">说点什么...</p>
                            </el-button>
                            <div v-if = "userID !== AuthorID">
                            <el-button v-if = "adoptState === 1" type="warning" color="#FFD466" class="large-button2" @click="turnto17">申 请</el-button>
                            <el-button v-if="adoptState !== 1" disabled type="warning" color="#FFD466" class="large-button2">{{adoptText}}</el-button>
                            <el-dialog  v-model = "modal17Visible1">
                                <applyAdopt :visible = "modal17Visible1"  @close="modal17Visible1 = false" @adoptStatus="adoptStatus"/>
                            </el-dialog>
                            </div>
                            <div v-else>
                                <span style="flex-grow: 1; margin-right: 80px;"></span>
                            </div>
                        </div>
                        <div v-if="isInputVisible" class="input-box-wrapper" style="flex: 1; z-index: 1;">
                            <div class="input-box-container">
                                <el-scrollbar class="input-scrollbar">
                                    <el-input
                                        type="textarea"
                                        :rows="inputRows"
                                        v-model="inputText"
                                        :placeholder= "PlaceholderText"
                                        @input="adjustInputRows"
                                    />
                                </el-scrollbar>
                            </div>
                            <div class="button-group">
                                <el-button type="warning" color="#FFD466" class="large-button1 " @click="sendMessage">发送</el-button>
                                <el-button type="info" class="large-button1 "  @click="toggleToInput">取消</el-button>
                            </div>
                        </div>
                        <div v-if="!isInputVisible">
                            <label class="container">
                                <input type="checkbox" v-model = "isChecked" @change="passageLike">
                                <div class="checkmark">
                                    <svg viewBox="0 0 256 256">
                                        <rect fill="none" height="256" width="256"></rect>
                                        <path class="like" d="M224.6,51.9a59.5,59.5,0,0,0-43-19.9,60.5,60.5,0,0,0-44,17.6L128,59.1l-7.5-7.4C97.2,28.3,59.2,26.3,35.9,47.4a59.9,59.9,0,0,0-2.3,87l83.1,83.1a15.9,15.9,0,0,0,22.6,0l81-81C243.7,113.2,245.6,75.2,224.6,51.9Z"
                                              stroke-width="18px" stroke="#000000" fill="none"></path></svg>
                                </div>
                            </label>
                        </div>
                        <p v-if="!isInputVisible" style="font-family: Arial, sans-serif; font-size: 22px; margin-left:-8px; margin-top: 30px; "> {{ counter }}</p>
                        <el-icon v-if="!isInputVisible" :size="25" style="margin-top : 5px" @click="firstcomment">
                            <ChatDotRound />
                        </el-icon>
                        <p v-if="!isInputVisible" style="font-family: Arial; font-size: 22px;margin-left:-10px; margin-right: 10px; margin-top: 30px;"> {{ textcounter }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {ref, defineEmits,onMounted} from 'vue';
import applyAdopt from './applyAdopt.vue';
import CommentList from '@/components/CommentList.vue';
import router from "@/router";
import axios from "axios";
import {ElMessage} from "element-plus";
const token = ref('');
const imageUrls = ref([])     //1]
//右边第一块
const UName = ref('用户名');   //2
const AuthorID = ref(1);    //3
const PassageID = ref(0);
const isFollowed = ref(0); //4 是否关注
// 定义按钮文本的响应式数据
const buttonText = ref('关 注');
const isFollow = ref(false);
// 设置axios的默认请求头，用于后续请求携带token
axios.defaults.headers.common['Authorization'] = ` ${token.value}`;
const avaClick = () => {
    const data = { id:AuthorID.value };
    sessionStorage.setItem('userData', JSON.stringify(data));
    router.push({
        path:'/UserPage',
        query: {
            id: AuthorID.value,
        }
    })
}
const handleFollowClick = async () => {
    const action = isFollowed.value === 1 ? 'delete' : 'add';
    try {
        const response = await axios.post(`http://localhost:8080/focus/${action}`, {
            FocusID: AuthorID.value });
        if (response.status === 200) {
            if(action === 'add'){
                isFollowed.value = 1;
                isFollow.value = true;
                ElMessage({
                    message: '关注成功',
                    type: 'success',
                    style: 'font-size:25px;font-weight:bold;',
                    offset: 55,
                    grouping:true
                })
            }
            else{
                isFollowed.value = 2;
                isFollow.value = false;
                ElMessage({
                    message: '取消关注成功',
                    type: 'success',
                    style: 'font-size:25px;font-weight:bold;',
                    offset: 55,
                    grouping:true
                })
            }
            buttonText.value = isFollow.value ? '已关注' : '关 注';
        } else {
            console.error('操作失败:', response.data.message);
            ElMessage({
                message: '操作失败，请再次尝试',
                type: 'error',
                style: 'font-size:25px;font-weight:bold;',
                offset: 55,
                grouping:true
            })
        }
        console.log(isFollow.value)
    } catch (error) {
        console.error('请求失败:', error);
        ElMessage({
            message: '操作失败，请再次尝试',
            type: 'error',
            style: 'font-size:25px;font-weight:bold;',
            offset: 55,
            grouping:true
        })
    }
};
//右边第二块
const title = ref('总标题');  //5
const ProfilePhoto = ref('')
const content = ref('');  //6
const vocation = ref('广东省珠海市') ; //7
const time = ref('2024年12月7日 16:10');  // 8
//右边第三块
// 评论数据
const comments = ref([]);
const ReplyUserID = ref(0);  //被回复的评论ID
const CommentReplylD = ref(0) //被回复评论的用户ID
const ParentID = ref(0);  //顶级评论ID
const replyType = ref(0);   //回复的类型
const PlaceholderText = ref('');
//评论的回复，类型还没确定
const toggleReplies = (commentIndex,parentID,commentID,replyUserID,username,type) => {
    CommentReplylD.value = commentID;
    ReplyUserID.value = replyUserID;
    ParentID.value = parentID;
    replyType.value = type;
    PlaceholderText.value = '回复'+username;
    toggleToInput();
};
const updateTextCounter = (newValue) => {
    textcounter.value = newValue;
};
//右边第四块
const textcounter = ref(0);
const isInputVisible = ref(false);
const inputText = ref('');  //评论
const inputRows = ref(1); // 初始行数
const userData0 = JSON.parse(sessionStorage.getItem('token'));
const userID = userData0.userID;
const adoptState = ref(0);
const adoptText = ref('');

//第一条评论
const firstcomment = () =>{
    replyType.value = 1 ; //返回第一条评论类型
    ReplyUserID.value = 0; // 清零
    ParentID.value = 0;
    CommentReplylD.value = 0;
    ReplyUserID.value = 0;
    PlaceholderText.value = '请输入内容';
    toggleToInput();
}
const toggleToInput = () => {
    isInputVisible.value =!isInputVisible.value;
    if (!isInputVisible.value) {
        inputText.value = '';
        inputRows.value = 1;
    }
};

//跳转页面
const modal17Visible1 = ref(false);
const turnto17 = () => {
    modal17Visible1.value = true;
};  //跳转到applyAdopt.vue

/// 发送消息的方法
const sendMessage = async () => {
    if (inputText.value.trim() === '' ) {
        // 进行简单验证，如果输入内容为空，则提示用户
        ElMessage({
            message: '请输入内容',
            type: 'error',
            style: 'font-size:25px;font-weight:bold;',
            offset: 55,
            grouping:true
        })
        return;
    }
    const dataToSend = {
        PassageID: PassageID.value,    //文章ID
        ReplyUserID: ReplyUserID.value,  //评论用户ID
        CommentContent: inputText.value,    //评论内容
        CommentType: replyType.value,  //评论类型
        ParentId : ParentID.value ,  //父评论ID
        CommentReplyID : CommentReplylD.value,//评论发布者的ID
    };
    try {
        const response = await axios.post('http://localhost:8080/comment/upload', dataToSend);
        console.log('消息发送成功，后端返回：', response.data);
        ElMessage({
            message: '评论成功',
            type: 'success',
            style: 'font-size:25px;font-weight:bold;',
            offset: 55,
            grouping:true
        })
        inputText.value = '';
        inputRows.value = 1;
        // 调用toggleToInput函数切换回输入状态，这里简单实现为清空输入框内容，可根据实际功能调整
        toggleToInput();
        textcounter.value++;
        replyType.value = 0 ; //返回第一条评论类型
        ReplyUserID.value = 0; // 清零
        const response1 = await axios.get('http://localhost:8080/comment/list/' + PassageID.value, {});
        if(response1.status === 200) {
            comments.value = response1.data.data;
        }
    } catch (error) {
        console.error('消息发送失败：', error);
        alert('消息发送失败，请再次尝试');
    }
};
// 调整输入框高度的方法
const adjustInputRows = () => {
    const lines = inputText.value.split('\n').length;
    inputRows.value = Math.max(lines, 1);
};
// 爱心 用于绑定复选框的选中状态
const isChecked = ref(false);
// 用于记录点击次数的计数器
const counter = ref(0);    //8
// 监听复选框的变化，当选中时增加计数器的值
const passageLike = async() => {
  if (isChecked.value) {
    try {
      const response = await axios.post('http://localhost:8080/likes/passage/add', {
        PassageID: PassageID.value
      });
      if (response.status === 200) {
        counter.value++;
        sessionStorage.setItem('likeNum',counter.value)
        emit('likeEvent', isChecked.value);
        ElMessage({
          message: '点赞成功',
          type: 'success',
          style: 'font-size:25px;font-weight:bold;',
          offset: 55,
          grouping:true
        })
      }
    } catch (error) {
      ElMessage({
        message: '点赞失败，请再次尝试',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        offset: 55,
        grouping:true
      })
      isChecked.value = false; // 点赞失败，将isChecked恢复为false
      emit('likeEvent', isChecked.value);
      return; // 直接返回，不再执行后续取消点赞相关逻辑
    }
  } else {
    // 只有点赞成功过，才执行取消点赞操作
    try {
      const response = await axios.post('http://localhost:8080/likes/passage/undo', {
        PassageID: PassageID.value
      });
      if (response.status === 200) {
        counter.value--;
        sessionStorage.setItem('likeNum',counter.value)
        emit('likeEvent', isChecked.value);
        ElMessage({
          message: '取消点赞成功',
          type: 'success',
          style: 'font-size:25px;font-weight:bold;',
          offset: 55,
          grouping:true
        })
      }
    } catch (error) {
      isChecked.value = true;
      ElMessage({
        message: '取消点赞失败，请再次尝试',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        offset: 55,
        grouping:true
      })
      emit('likeEvent', isChecked.value);
      return;
    }
  }
}
const adoptStatus = () =>{
    adoptState.value = -1;
    adoptText.value = '已申请';
}
const UserAvatar = ref('');
onMounted(async () => {
    setTimeout(async() => {
    const userData = JSON.parse(sessionStorage.getItem('token'));
    token.value = userData.token;
    const response3 = await axios.get('http://localhost:8080/users/'+ userData.userID,{})
    if(response3.status==200){
        UserAvatar.value = response3.data.ProfilePhoto;
    }
    const userData1 = JSON.parse(sessionStorage.getItem('AdoptPassageID'));
    PassageID.value = userData1.PassageID;
    axios.defaults.headers.common['Authorization'] = `${userData.token}`;
    const response = await axios.get('http://localhost:8080/passage/content/'+ PassageID.value,{} );// 获取用户名
    console.log(response.data);
    AuthorID.value = response.data.AuthorID;   //作者ID 1
    UName.value = response.data.UName;         //作者名称 2
    ProfilePhoto.value = response.data.ProfilePhoto;   //作者头像
    isFollowed.value = response.data.ifSubscribe;  //是否关注 3
    buttonText.value = isFollowed.value === 1  ? '已关注' : '关 注';
    isFollow.value = isFollowed.value === 1  ? true : false;
    title.value = response.data.PassageTitle;   //标题 4
    content.value = response.data.PassageContent;  //内容 5
    vocation.value = response.data.PassageArea;  //地区 6
    time.value = response.data.PassageTime; //发布时间 7
    imageUrls.value = response.data.PassagePicList;  // 8
    textcounter.value = response.data.CommentNum;  //评论数 9
    setTimeout(() => {
      counter.value = sessionStorage.getItem('likeNum') //点赞数  10
      console.log("子组件点赞数：",counter.value)
    },50)
    isChecked.value = response.data.ifLiked//是否点赞  11

    const response1 = await axios.get('http://localhost:8080/comment/list/' + userData1.PassageID, {});
    if(response1.status == 200) {
        comments.value = response1.data.data;
    }
    const response2 = await axios.get('http://localhost:8080/adopt/application/getApplicationStatus/' + userData1.PassageID + '/' + userData.userID, {});
    console.log(response2.data);
    if(response2.status == 200) {
        adoptState.value = response2.data.status;
        if(adoptState.value == 1)
            adoptText.value = '申请';
        else if(adoptState.value == -1)
            adoptText.value = '已申请';
        else if(adoptState.value == 2)
            adoptText.value = '已领养';
    }
    },1)
})
// 定义关闭模态框的方法并向父组件发送关闭事件
const closeModal = () => {
    emit('close');
    inputText.value = '';
    isInputVisible.value = true;
    toggleToInput();
};
// 定义 emits
const emit = defineEmits(['close','likeEvent','adoptStatus']);
</script>

<style scoped>
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
}
.modal-content {
    background: white;
    padding: 20px;
    border-radius: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    width: 70%; /* 设置宽度为页面的60% */
    height: 80%; /* 设置高度为页面的80% */
    overflow: auto;
}
.rounded-rectangle {
    border-radius: 20px; /* 圆弧长方形 */
    background: white;
    text-align: center;
    width: 100%; /* 设置宽度为页面的80% */
    height: 100%; /* 设置高度为页面的80% */
    margin: auto; /* 自动居中 */
    display: flex; /* 使用 Flexbox 布局 */
    position: relative; /* 相对定位，用于绝对定位关闭按钮 */
}
.leftrounded, .rightrounded {
    flex: 1; /* 左右两部分各占一半宽度 */
    width: 98%; /* 设置宽度为页面的100% */
    height: 98%; /* 设置高度为页面的100% */
}
.carousel-image {
    width: 100%;
    height: 100%;
    object-fit: contain; /* 保持图片比例并填充容器 */
}
.el-carousel {
    width: 100%;
    height: 100%;
}
.el-carousel__item h3 {
    color: #475669;
    opacity: 0.75;
    line-height: 500px;
    margin: 0;
}
.rightrounded {
    background: white; /* 右边部分的背景颜色 */
    border-radius: 20px; /* 圆弧长方形 */
    display: flex;
    flex-direction: column; /*竖直排布*/
    justify-content: center; /*居中*/
    margin-left: 20px;
    padding-bottom: 30px;
}
.right-content-scrollbar {
    height: 100%; /* 设置滚动条容器高度占满父容器 */
    overflow: auto; /* 当内容超出时显示滚动条 */
    margin-right : -10px;
}
.el-avatar{
    cursor: pointer;
}
.followed-button {
    background-color: #A6A6A6;
    border-color: #A6A6A6;
}
.followed-button:hover{
  background-color: #BCBCBC;
  border-color: #BCBCBC;
  color:white;
}
.large-button {
  width:75px;
  height:35px;
  border-radius: 11px;
  font-size: 16px;
  margin-right: 20px;
  color:white;
  font-weight: bold;
}
.large-button:hover{
  color:white;
}
/*右边第二块文字格式*/
.title-section {
    display: flex;
    justify-content: flex-start;
    text-align: left;
    margin-top: 15px;
}
.text-box {
    display: flex;
    flex-direction: column;
    position: relative;
}
.title {
    font-size: 25px;
    font-weight: bold;
    text-align: left;
    margin-bottom: 2px;
    margin-top: -8px;
}
.content {
    font-size: 17px;
    text-align: left;
    margin-bottom: 5px;
    margin-left: 6px;
    margin-right: 14px;
}
.vocation{
    font-size: 15px;
    margin-right: 20px;
}
/*第三个评论区*/
.comments{
    margin-bottom: 10px;
}
/*第四块评论框*/
.button-container-section{
    margin-top: 10px;
    margin-bottom: -10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.custom-button {
    width: 250px; /* 调整按钮宽度 */
    height: 50px; /* 调整按钮高度 */
    background-color: #ebebeb; /* 灰色背景 */
    border-color: #ebebeb; /* 边框颜色与背景一致 */
    color: #333; /* 文字颜色 */
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: -10px;
}
.custom-button:hover {
    background-color: #D3D3D3; /* 一种浅灰色的十六进制表示 */
    border-color: #D3D3D3;  /* 边框颜色与背景一致 */
}
.comment-apply{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: -10px;
}
.large-button2{
    font-size: 1.3em; /* 放大按钮 */
    padding: 18px 20px; /* 增加按钮的内边距 */
    width: 110px;
    font-weight: bold;
    color:white;
    border-radius: 10px;
    height:40px;
    margin-left: 20px;
    margin-right:-10px;
    text-align: center;
}
.large-button2:hover{
  color:white;
}
/*like动效*/
/* From Uiverse.io by KSAplay */
.container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
}
.container {
    display: block;
    position: relative;
    cursor: pointer;
    user-select: none;
    transition: 100ms;
    /*margin : auto;*/
    margin-left : 10px;
    margin-top : 5px;
}
.checkmark {
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    transition: 100ms;
    animation: dislike_effect 500ms ease;
    margin-left: 5px;
}
.container input:checked ~ .checkmark path {
    fill: #FFD466;
    stroke-width: 0;
}
.container input:checked ~ .checkmark {
    animation: like_effect 400ms ease;
}
.container:hover {
    transform: scale(1.2);
}
.container:hover .like{
    stroke:#FFD466;
}
@keyframes like_effect {
    0% {
        transform: scale(0);
    }
    50% {
        transform: scale(1.2);
    }
    100% {
        transform: scale(1);
    }
}
@keyframes dislike_effect {
    0% {
        transform: scale(0);
    }
    50% {
        transform: scale(1.2);
    }
    100% {
        transform: scale(1);
    }
}

.full-size-scrollbar {
    height: 100%; /* 设置高度为100% */
}
.el-icon{
    cursor: pointer;
}
.button-group {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
}
.large-button1 {
    font-size: 15px; /* 放大按钮 */
    width:60px;
    border-radius: 10px;
    color:white;
    height:35px;
    font-weight:bold;
}
.large-button1:hover{
    color:white;
}
</style>
